package com.yy.controller;

import com.google.gson.Gson;
import com.yy.entity.Invoice;
import com.yy.entity.OcrResult;
import com.yy.entity.Result;
import com.yy.service.InvoiceService;
import com.yy.utils.AccessToken;
import com.yy.utils.ContactRecoOcr;
import com.yy.utils.DateToStr;
import com.yy.utils.PDFUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.Swagger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("invoice")
@Api(tags = "发票接口相关")
public class InvoiceController {
    private String basePath = System.getProperty("user.dir") + File.separator + "src/main/resources/static/file/upload";

    @Value("${invoice.name}")
    private String userName;
    @Autowired
    private InvoiceService invoiceService;

    /**
     * 上传pdf文件 并且将发票识别之后修改文件名
     * @param files
     * @return
     */
    @ApiOperation(tags = "上传发票",value = "/invoice/uploadPdfs",httpMethod = "GET" ,response = Result.class)
    @PostMapping("uploadPdfs")
    public Result uploadPdfs(@ApiParam("上传的文件") @RequestParam("file") MultipartFile[] files){
        String token = AccessToken.accessToken("7984806f8323444799290592997b56f2", "a77f00d4dce043f6a827c6116587e5e4");
        //遍历所有文件
        List<Map<String,String>> details = new ArrayList();
        Result res = new Result();
        res.setCode(0);
        res.setMessage("success");
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            File tempPdf = null;
            //如果是pdf再将其进行保存
            if(originalFilename.endsWith(".pdf")){
                try {
//                    将还没有识别的文件放入temp文件夹中
                    File test = new File(basePath + "\\temp");
                    if(!test.exists()){
                        test.mkdir();
                    }
                    tempPdf = new File(basePath + "\\temp\\"+originalFilename);
//                    保存文件
                    file.transferTo(tempPdf);
                    //将文件转换成png格式
                    String photo = PDFUtil.pdfToPhoto1(tempPdf.getAbsolutePath());
                    String taskId = ContactRecoOcr.getTaskId(photo, token);
                    String result = "";
                    while (true) {
                        result = ContactRecoOcr.vatInvoiceRecoOcrResult(taskId, token);
                        boolean yes = result.contains("\"status\":\"processing\"");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        if (!yes) break;
                    }
//                    System.out.println(result);
                    Gson gson = new Gson();
                    Invoice invoice = new Invoice();
                    OcrResult ocrResult = gson.fromJson(result, OcrResult.class);
                    String totalAmount = ocrResult.getData().getObjs().get(0).getResult().getTotalAmount();
                    String invoiceDate = ocrResult.getData().getObjs().get(0).getResult().getInvoiceDate();
                    //将日期转换出来 作为后期的目录
                    invoiceDate = DateToStr.myDate(invoiceDate);
                    String invoiceCode = ocrResult.getData().getObjs().get(0).getResult().getInvoiceCode();
                    String invoiceNum = ocrResult.getData().getObjs().get(0).getResult().getInvoiceNum();
                    String invoiveName = ocrResult.getData().getObjs().get(0).getResult().getInvoiceName();
                    invoice.setTotalAmount(totalAmount);
                    invoice.setInvoiceDate(invoiceDate);
                    invoice.setInvoiceCode(invoiceCode);
                    invoice.setInvoiceName(invoiveName);
                    invoice.setInvoiceNum(invoiceNum);
                    Integer save = invoiceService.save(invoice);
                    while (save != 1){
                        res.setMessage(res.getMessage() + invoiceCode + "插入有问题");
                    }
                    String invoicePath = basePath + "\\" + invoiceDate.substring(0,6);
//                    System.out.println(invoicePath);
                    File invoices = new File(invoicePath);
                    if(!invoices.exists()){
                        invoices.mkdir();
                    }
                    //设置文件的名称
                    tempPdf.renameTo(new File(invoicePath + "\\"+userName+"-公务费-" + totalAmount + ".pdf"));
                    HashMap<String, String> map = new HashMap<>();
                    map.put(file.getOriginalFilename(),totalAmount + "元");
                    details.add(map);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            else {
                HashMap<String, String> errorMap = new HashMap<>();
                errorMap.put(file.getOriginalFilename(),"error");
                details.add(errorMap);
            }
        }
        File endFile = new File(basePath + "\\temp");
        for (File file : endFile.listFiles()) {
            file.delete();
        }
        if(!details.isEmpty()){
            res.setData(details);
        }
        return res;
    }

//    @GetMapping("sum/{date}")
//    public BigDecimal sum(@PathVariable("date") String date){
//        String sumPath = basePath + File.separator + date;
//        BigDecimal bigDecimal = new BigDecimal("0.00");
//        String[] files = new File(sumPath).list();
//        System.out.println(files);
//        for (String fileName : files) {
////            杨宇-公务费-3.50.pdf
//            String money = fileName.split("-")[2].substring(0,fileName.split("-")[2].lastIndexOf(".pdf"));
//            bigDecimal = bigDecimal.add(new BigDecimal(money));
//        }
//        return bigDecimal;
//    }

    @ApiOperation(tags = "统计每个月份的发票金额",httpMethod = "GET",response = Result.class, value = "invoice/sum/{date}")
    @GetMapping("sum/{date}")
    public Result sum(@ApiParam(required = true,name = "年月",value = "202207") @PathVariable("date") String date){
        try {
            return new Result().success(invoiceService.selectByDate(date));
        }catch(Exception e){
            return new Result().error();
        }
    }

}
